from . import user_blue
from flask import *
from info.utils.captcha.captcha import captcha
from info import redisSession
from info.utils import validate_request as vr
from info.utils.sms import smsClient
import random
from info.models import *
from info.utils.encript import *
from sqlalchemy import and_
# from werkzeug.utils import secure_filename

"""
    imageid
    生成image图片和image_code
    把image_code保存到redis中
    返回图片
    得到验证码标识
"""
@user_blue.route('/user/image_code')
def image_code_handler():
    imageid = request.args.get('imageid')
    # 判断标识是否合法
    error_imageid = vr.v_imageid(imageid)
    if error_imageid:return error_imageid
    # 生成验证码
    name,image_code,image = captcha.generate_captcha()
    # ------
    print(image_code)
    # ------
    # 写入redisSession
    redisSession.set_image_code(imageid,image_code)
    # 生成图片字节流，并返回图片
    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpg'
    return response



"""
    得到的参数：
        imageid
        tel
        image_code
    验证码是否正确
        1.过期
        2.不正确
    校验手机号是否被注册 #todo
    生成手机验证码
    通过第三发发送
    手机验证码写入redisSession
    :return '200’
"""
@user_blue.route('/user/tel_code')
def tel_code_handler():
    imageid = request.args.get('imageid')
    tel = request.args.get('tel')
    image_code = request.args.get('image_code')

    error_imageid = vr.v_imageid(imageid)
    if error_imageid:return error_imageid

    error_tel = vr.v_tel(tel)
    if error_tel:return error_tel

    session_image_code = redisSession.get_image_code(imageid)
    error_image_code = vr.v_image_code(image_code,session_image_code)
    if error_image_code:return error_image_code

    if User.query.filter(User.tel == tel).first():
        return vr.existed
    # todo 检查手机号是否被注册
    tel_code = random.randint(100000,999999).__str__()
    # -------
    print(tel_code)
    # -------
    sms_ret = smsClient.singleSend(tel,tel_code)
    error_sms = vr.v_sms(sms_ret)
    if error_sms:return error_sms
    redisSession.set_tel_code(tel,tel_code)
    return vr.sucess

"""
    :param
        tel
        tel_code
        password
    tel是否被注册
    插入数据库
"""
@user_blue.route('/user/register',methods=['post'])
def register_handler():
    tel = request.form.get('tel')
    tel_code = request.form.get('tel_code')
    password = request.form.get('password')


    error_tel = vr.v_tel(tel)
    if error_tel:return error_tel

    session_tel_code = redisSession.get_tel_code(tel)
    error_tel_code = vr.v_tel_code(tel_code,session_tel_code)
    if error_tel_code:return error_tel_code

    error_password = vr.v_password(password)
    if error_password:return error_password

    if User.query.filter(User.tel == tel).first():
        return vr.existed
    # todo 检查是否被注册
    user = User(tel=tel,password=md5(password))
    db.session.add(user)
    try:
        db.session.commit()
        session['user'] = user.username
        return vr.sucess
    except:
        db.session.rollback()
        return vr.failure


"""
登录，tel,password
"""
@user_blue.route('/user/login',methods=['post'])
def login_handler():
    tel = request.form.get('tel')
    password = request.form.get('password')
    #验证手机号
    error_tel = vr.v_tel(tel)
    if error_tel: return error_tel
    #验证密码
    password_error = vr.v_password(password)
    if password_error: return password_error
    #查询数据库
    user = User.query.filter(and_(User.tel==tel,User.password==md5(password))).first()
    if not user:
        return vr.WRONG_CONTENT
    user.lastLoginDatetime = datetime.now()
    try:
        db.session.add(user)
        db.session.commit()
        # 刷新，不然报错=======就这么用，不懂为啥
        db.session.merge(user)
        db.session.refresh(user)
        # ======================================
    except:
        return vr.failure
    session['user_id'] = user.id
    return vr.sucess

#用户注销
@user_blue.route('/user/logout')
def logout_handler():
    session.pop('user_id')
    return redirect(url_for('index.index_handler'))

@user_blue.route('/user/info')
def info_handler():

    user:User = User.query.filter(User.id==session.get('user_id')).first()
    if user:
        return render_template('news/user.html',user=user)
    return vr.error

# @user_blue.route('/user/base_info')
# def base_info_handler():
#     user: User = User.query.filter(User.id == session.get('user_id')).first()
#     if user:
#         return render_template('news/user_base_info.html',user=user)
#     return vr.error

@user_blue.route('/user/pic_info',methods=['post','get'])
def pic_info_handler():
    user: User = User.query.filter(User.id == session.get('user_id')).first()
    if request.method == 'GET':
        if user:
            return render_template('news/user_pic_info.html',user=user)
        return vr.error
    else:
        # if 'avatar' not in request.files:
        #     return vr.error
        # # elif image.filename[image.filename.rfind('.'):] :
        # #     suffix_name = image.filename[image.filename.rfind('.'):]
        # else:
        file = request.files['avatar']
        if not file:
            return vr.error
        # #检验文件大小
        # file_size_error = vr.v_filesize(len(file.read()))
        # if file_size_error: return file_size_error
        # #检验文件类型
        # file_name_error = vr.v_filename(secure_filename(file.filename))
        # if file_name_error:return file_name_error

        #检验文件
        file_error = vr.v_file(file)
        if file_error:return file_error

        #文件上传路径
        basepath = 'info/static/user_image/'
        #保存图片，格式统一为png
        file.save(basepath+user.uid+'.png')
        #文件获取路径
        user.image_url = '/static/user_image/'+user.uid+'.png'
        try:
            db.session.add(user)
            db.session.commit()
            #刷新，不然报错=======就这么用，不懂为啥
            db.session.merge(user)
            db.session.refresh(user)
            #======================================
        except:
            db.session.rollback()
            return vr.failure
        return vr.sucess




